package pro.survey.analyzer.imp.window;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import pro.survey.analyzer.AnalyticsEngine;
import pro.survey.analyzer.GUIGenerator;
import pro.survey.analyzer.HibernateUtil;
import pro.survey.analyzer.Trans;
import pro.survey.analyzer.data.Imports;
import pro.survey.analyzer.lectors.window.LectorsWindow;

/**
 *
 * @author Adrian
 */
public class ButtonOK extends Button{
    
    private String selectedItem;

    public void setSelectedItem(String selectedItem) {
        this.selectedItem = selectedItem;
    }

    public String getSelectedItem() {
        return selectedItem;
    }
    
    public ButtonOK(final Stage dialogStage) {
        this.setText(GUIGenerator.getInstance().getLocaleText(Trans.SELECT));
        this.setDisable(true);
        this.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                dialogStage.close();
                try {
                    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(selectedItem);
                    SimpleDateFormat year = new SimpleDateFormat("yyyy");
                    SimpleDateFormat month = new SimpleDateFormat("MM");
                    SimpleDateFormat day = new SimpleDateFormat("dd");
                    SimpleDateFormat h = new SimpleDateFormat("HH");
                    SimpleDateFormat m = new SimpleDateFormat("mm");
                    List<Imports> imports = HibernateUtil.getSession().createQuery(
                    "from Imports as imp where YEAR(imp.created) = ? AND MONTH(imp.created) = ? AND DAY(imp.created) = ? AND HOUR(imp.created) = ? AND MINUTE(imp.created) = ?").
                            setString(0, year.format(date)).
                            setString(1, month.format(date)).
                            setString(2, day.format(date)).
                            setString(3, h.format(date)).
                            setString(4, m.format(date)).
                            list();
                    AnalyticsEngine.getInstance().setImport(imports.get(0));
                    LectorsWindow.getInstance().init(imports.get(0).getId());
                } catch (ParseException ex) {
                    Logger.getLogger(ButtonOK.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}
